'use strict'

function isObject(o) {
  return Object.prototype.toString.call(o) === '[object Object]'
}

function spinnerStart(msg, spinnerString = '|/-\\') {
  const Spinner = require('cli-spinner').Spinner
  const spinner = new Spinner(msg + ' %s')
  spinner.setSpinnerString(spinnerString)
  spinner.start()
  return spinner
}

function exec(command, args, options) {
  const win32 = process.platform === 'win32'
  const cmd = win32 ? command : command
  const cmdArgs = win32 ? args : args
  // const cmd = win32 ? command + '.cmd' : command
  // const cmdArgs = win32 ? ['/c'].concat(command) : args

  // console.log(cmd, cmdArgs)

  return require('child_process').spawn(cmd, cmdArgs, options || {})
}

function execAsync(command, args, options) {
  return new Promise((resolve, reject) => {
    const p = exec(command, args, options)
    p.on('error', (e) => {
      console.log(e)
      reject(e)
    })
    p.on('exit', (c) => {
      resolve(c)
    })
  })
}

function execAsyncInstall(command, args, options) {
  function baseExec(command, args, options) {
    const win32 = process.platform === 'win32'
    const cmd = win32 ? command + '.cmd' : command
    return require('child_process').spawn(cmd, args, options || {})
  }
  return new Promise((resolve, reject) => {
    const p = baseExec(command, args, options)
    p.on('error', (e) => {
      reject(e)
    })
    p.on('exit', (c) => {
      resolve(c)
    })
  })
}

/**
 *
 * @param {*} timeout 睡眠时间
 * @returns Promise
 */
function sleep(timeout = 1000) {
  return new Promise((resolve) => setTimeout(resolve, timeout))
}

module.exports = { isObject, spinnerStart, sleep, exec, execAsync,execAsyncInstall }
